<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use DB;
use Cache;
use Log;

class PublicController extends Controller
{
    //登录
    public function login() {
        $params = request()->all();
        // Log::info($params);
        $num = $params['num'];
        $password = $params['password'];
        if(!$num || !$password){
            return "工号或密码错误！";
        }
        $exists = DB::table('manager')->where(['num'=>$num,'password2'=>$password])->exists();
        $res = $exists ? "1" : "工号或密码错误！";
        return $res;
    }

    //首页
    public function index() {
        $data = [
            [
                'name' => '受 理',
                'url'  => route('appScanList'),
                'img'  => [
                    '二维码' => '/admin/static/app/erwei.png',
                    'ID码' => '/admin/static/app/rfid.png'
                ]
            ],
            [
                'name' => '不合格/斗臂车拍照',
                'url'  => route('appPhoto'),
                'img'  => [
                    '拍照' => '/admin/static/app/camera.png',
                ]
            ],
        ]; 
        return view('app.public.index', compact('data'));
    }

    //扫描列表
    public function scanList() {
        $data = [];
        //post->请求扫描数据（RFID或二维码扫描）
        if(request()->isMethod('post')) {
            Log::info(request()->all());
            $id = request('id', '');
            $contract_id = request('contract_id', '');
            $batchNum = request('batchNum', '');
            $code = request('code', '');
            $gqjID = request('gqj_ID', '');
            if($batchNum) {
                $contract_id = DB::table("a_contract")->where("batchNum",$batchNum)->value('id');
            }
            if(!$contract_id) {
                return out(0, '请先指定受理批次！');
            }
            #region sample_info条件
            if($id) {
                $scanCode = 1;
                $where = [
                    ['a.id', '=', $id],
                    ['a.key', '=', request('k', '')],
                    ['c.is_del', '=', 0],
                ];
            }
            elseif($code) {
                $scanCode = 1;
                $where = [
                    ['a.bar_code', '=', $code],
                    ['c.is_del', '=', 0],
                ];
            }elseif($gqjID){
                $where = [
                    ['a.gqj_ID', '=', $gqjID],
                    ['c.is_del', '=', 0],
                ];
            }else{
                $where = [];
            }
            if(!$where){
                return out(0,"请指定搜索条件！");
            }
            #endregion
            $data = DB::table('a_sample_info as a')
            ->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')
            ->leftJoin('a_contract as c', 'a.contract_id', '=', 'c.id')
            ->where($where)
            ->select('a.id', 'a.bar_code','a.gqj_ID', 'a.bar_code_1st', 'a.res', 'a.contract_id', 'b.tool_name')
            ->orderBy('a.id','desc')->first();

            //return out中code=2页面判断拒绝再次请求
            if(!$data) {
                return out(2, '数据不存在！');  
            }
            //如果是扫二维码或条形码，则判断他们的bar_code_1st是不是已经存在批次中
            if(isset($scanCode)){
                $exists = DB::table('a_sample_info')->where(['contract_id'=>$contract_id,'bar_code_1st'=>$data->bar_code_1st])->exists();
            }
            //判断样品是否已受理
            if($data->res == 0 || $data->contract_id == $contract_id || (isset($exists) && $exists)){
                Log::info($data->res);
                return out(2, '样品受理中！');  
            }
            
            return out(1, '请求成功！', $data);
        }
        return view('app.public.scan.list', compact('data'));
    }

    //不合格/斗臂车照片
    public function photo() {
        return redirect(name_admin().'/photo/list');
    }

    //受理批次-列表
    public function contract() {
        Log::info("contract");
        $data = DB::table('a_contract')->where('is_del', 0)->where('status', '<', 11)->select('batchNum', 'client_name', 'created_at', 'id')->orderBy('id', 'desc')->get();
        if(request('from') == 'app') {
            return out(1, '请求成功', $data);
        }
        return view('app.public.contract', compact('data'));
    }

    //提交受理
    public function gaiyao() {
        Log::info("-------------------扫码受理-------------------------");
        Log::info(request()->all());
        if(request()->isMethod('post')){
            #region 数据校验
            $batchNum = request('batchNum', '');
            if(!$batchNum) {
                return '请先选择受理批次！';     
            }
            $sampleIds = request('sampleIds', []);
            $gqj_IDs = request('gqj_IDs', '');
            if(!$sampleIds && !$gqj_IDs) {
                return '请先扫码进行录入！';
            }
            #endregion
            #region 获取提交的试品的相关信息（gyid和info）
            if($sampleIds){
                $ids = array_unique(array_filter(array_keys($sampleIds)));
            }elseif ($gqj_IDs) {
                $gqj_IDs = array_unique(explode(',',$gqj_IDs));
                //检查该工器具是否已经存在该批次中
                $existGqjIds = DB::table('a_sample_info as a')->leftJoin('a_contract as b','a.contract_id','=','b.id')->where('b.batchNum',$batchNum)->whereIn('a.gqj_ID', $gqj_IDs)->distinct('a.gqj_ID')->pluck('a.gqj_ID')->toArray();
                $gqj_IDs = array_diff($gqj_IDs, $existGqjIds);
                $sample = DB::table('a_sample_info')->whereIn('gqj_ID', $gqj_IDs)->orderBy('id','desc')->distinct('gqj_ID')->pluck('id','gqj_ID')->toArray();
                $ids = array_values($sample);
            }
            $sampleInfos = DB::table('a_sample_info')->whereIn('id', $ids)->select('bar_code', 'contract_id', 'contract_gaiyao_id', 'self_num', 'manufacturer', 'production_date', 'guige_xinghao', 'brand', 'sample_status', 'gqj_ID', 'pipe_code', 'photo', 'place', 'bar_code_1st', 'third_id', 'batch_num_custom')->get();

            if (count($sampleInfos) == 0) {
                return "没有可受理的样品！";
            }
            Log::info($sampleInfos);
            $gyDetail = [];
            foreach($sampleInfos as $item) {
                $gyId = $item->contract_gaiyao_id;
                isset($gyDetail[$gyId]) ? ($gyDetail[$gyId][] = $item) : ($gyDetail[$gyId] = [$item]);
            }
            #endregion
            #region 概要信息分组
            $gyIds = array_keys($gyDetail);
            $gyInfos = DB::table('a_contract_gaiyao')->whereIn('id', $gyIds)->select('id', 'std_num', 'std_id', 'tool_name', 'tool_id', 'item_names', 'item_ids', 'voltage', 'vol_id', 'class', 'class_id', 'unit', 'remark')->get();
            $gyFz = [];
            foreach($gyInfos as $item) {
                $itemAry = (array)$item;
                ksort($itemAry);
                $id = $itemAry['id'];
                unset($itemAry['id']);
                $itemString = serialize($itemAry);
                isset($gyFz[$itemString]) ? ($gyFz[$itemString][] = $id) : ($gyFz[$itemString] = [$id]);
            }
            #endregion
            $chars_count = DB::table('setting')->where('id', '1')->value('chars_count');
            #region 添加的样品
            $contract = DB::table('a_contract')->where('batchNum', $batchNum)->first();
            try {
                DB::transaction(function() use ($gyFz, $gyDetail, $contract, $chars_count) {
                    $batchNum = $contract->batchNum;
                    $sampleData = $sampBarCodes = [];
                    $gy = DB::table('a_contract_gaiyao')->where('contract_id', $contract->id)->select('index', 'count')->orderBy('id', 'desc')->first();
                    $index = $gy ? $gy->index + $gy->count : 1;
                    $a=0;
                    foreach($gyFz as $oldGy => $gyIdAry) {
                        //添加样品概要
                        $newGy = unserialize($oldGy);
                        $newGy['count'] = 0;
                        $newGy['contract_id'] = $contract->id;
                        foreach($gyIdAry as $gyId) {
                            $newGy['count'] += count($gyDetail[$gyId]);
                        }
                        $newGy['index'] = $index;
                        $index += $newGy['count'];
                        $newGy['bar_codes'] = $this->gyBarCodes($chars_count, $batchNum, $newGy['count'], $newGy['index']);
                        $a += 1;
                        Log::info($a);
                        Log::info($newGy);
                        $contract_gaiyao_id = DB::table('a_contract_gaiyao')->insertGetId($newGy);
                        #region整理样品基本信息
                        $barcodeAry = explode('～', $newGy['bar_codes']);
                        $barcode = $barcodeAry[0];
                        foreach($gyIdAry as $k1 => $gyId) {   //$k1为默认下标0，1，2，3.。。。。
                            foreach($gyDetail[$gyId] as $k2 => $sample) {   //$k2为默认下标0，1，2，3.。。。。
                                if($k1 > 0 || $k2 > 0) {
                                    $barcode += 1;
                                }
                                $sampBarCodes[] = $barcode;
                                $sample->bar_code = $barcode;
                                $sample->contract_id = $contract->id;
                                $sample->contract_gaiyao_id = $contract_gaiyao_id;
                                $sample->bar_code_1st = $sample->bar_code_1st ?: $sample->bar_code;
                                $sampleData[] = (array)$sample;
                            }
                        }
                        #endregion
                    }
                    //添加样品基本信息
                    DB::table('a_sample_info')->insert($sampleData);
                    #region 整理样品试验项目
                    $newSample = DB::table('a_sample_info as a')->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')->whereIn('a.bar_code', $sampBarCodes)->select('a.id', 'a.contract_id', 'a.contract_gaiyao_id', 'b.item_ids', 'b.tool_id','b.std_id')->get();

                    $data_item = $data_input = [];
                    foreach($newSample as $sample) {
                        $itemIds = explode(',', $sample->item_ids);
                        foreach($itemIds as $itemId) {
                            $data_item[] = [
                                'contract_id'        => $sample->contract_id,
                                'contract_gaiyao_id' => $sample->contract_gaiyao_id,
                                'sample_info_id'     => $sample->id,
                                'item_id'            => $itemId,
                                'station_ids'        => DB::table('a_std_tool_item_rel')->where([
                                    'tool_id'     => $sample->tool_id,
                                    'testitem_id' => $itemId
                                ])->value('station_ids'),
                            ];
                            $testdata_key_ids = DB::table('a_testdata_key')
                                                ->where(['std_id'=>$sample->std_id,'tool_id'=>$sample->tool_id,'item_id'=>$itemId])
                                                ->pluck('id');
                            foreach ($testdata_key_ids as $testdata_key_id) {
                                $data_input[] = [
                                    'sample_info_id' => $sample->id,
                                    'testdata_key_id' => $testdata_key_id,
                                ];
                            }
                        }
                    }
                    #endregion
                    //添加样品试验项目
                    DB::table('a_item_data')->insert($data_item);
                    //添加input_data 试验数据
                    DB::table('a_input_data')->insert($data_input);
                });
            } catch(\Throwable $e) {
                return '添加失败'.$e->getMessage();
            }
            #endregion
            return "1";
        }
        
    }

    //退出登录
    public function logout() {   //删除用户信息
        auth('admin')->logout();
        //跳转到登录页面
        return redirect(route('loginAdmin'));
    }

    private function gyBarCodes($chars_count, $batch_num, $count = 1, $index = 1) {
        //格式化字符串
        $format_string = "%0{$chars_count}d";
        /* 制作条码范围-------------------------start */
        //开始的条码
        $str_start = $batch_num.sprintf($format_string, $index);
        //结尾的条码
        $str_end = $batch_num.sprintf($format_string, $index + $count - 1);
        $bar_codes = $str_start.'～'.$str_end;
        /* 制作条码范围-----------------------------end */
        return $bar_codes;
    }
}
